#!/usr/bin/env python3
"""
调试应用权限过滤
"""
import sys
import os

# 添加项目路径
project_root = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, project_root)

def check_permission_config():
    """检查权限配置"""
    from dbgpt.storage.metadata.db_manager import db
    from dbgpt_serve.auth.models.models import UserRoleEntity, RoleAppEntity, RoleEntity, UserEntity
    
    print("=" * 60)
    print("1. 检查sys_role_app表是否存在")
    print("=" * 60)
    
    with db.session() as session:
        try:
            # 测试查询
            result = session.execute("SHOW TABLES LIKE 'sys_role_app'")
            tables = result.fetchall()
            if tables:
                print("✓ sys_role_app 表存在")
            else:
                print("✗ sys_role_app 表不存在！")
                print("请先执行SQL创建表")
                return
        except Exception as e:
            print(f"✗ 检查表失败: {e}")
            return
    
    print("\n" + "=" * 60)
    print("2. 检查权限数据")
    print("=" * 60)
    
    with db.session() as session:
        # 查询所有权限配置
        role_apps = session.query(RoleAppEntity).all()
        if role_apps:
            print(f"✓ 找到 {len(role_apps)} 条权限配置:")
            for ra in role_apps:
                role = session.query(RoleEntity).filter(RoleEntity.id == ra.role_id).first()
                print(f"  - 角色: {role.role_name if role else 'Unknown'} (ID:{ra.role_id}) -> 应用: {ra.app_code}")
        else:
            print("✗ 没有权限配置数据！")
            print("请先执行SQL添加权限配置")
    
    print("\n" + "=" * 60)
    print("3. 检查所有用户的权限")
    print("=" * 60)
    
    with db.session() as session:
        users = session.query(UserEntity).filter(UserEntity.is_deleted == 0).all()
        
        for user in users:
            print(f"\n用户: {user.username} (ID:{user.id})")
            
            # 获取用户角色
            user_roles = (
                session.query(UserRoleEntity.role_id)
                .filter(UserRoleEntity.user_id == user.id)
                .all()
            )
            role_ids = [r[0] for r in user_roles]
            
            if not role_ids:
                print("  ⚠ 该用户没有角色")
                continue
            
            # 获取角色信息
            roles = session.query(RoleEntity).filter(RoleEntity.id.in_(role_ids)).all()
            print(f"  角色: {', '.join([r.role_name for r in roles])}")
            
            # 获取应用权限
            app_perms = (
                session.query(RoleAppEntity.app_code)
                .filter(RoleAppEntity.role_id.in_(role_ids))
                .distinct()
                .all()
            )
            app_codes = [a[0] for a in app_perms]
            
            if app_codes:
                print(f"  ✓ 应用权限: {', '.join(app_codes)}")
            else:
                print("  ℹ 无应用权限限制(可访问全部应用)")

def test_api_filter(user_id: int):
    """测试API过滤逻辑"""
    from dbgpt.storage.metadata.db_manager import db
    from dbgpt_serve.auth.models.models import UserRoleEntity, RoleAppEntity
    
    print("\n" + "=" * 60)
    print(f"4. 测试用户 {user_id} 的API过滤逻辑")
    print("=" * 60)
    
    with db.session() as session:
        # 查询用户的所有角色
        role_ids_query = (
            session.query(UserRoleEntity.role_id)
            .filter(UserRoleEntity.user_id == user_id)
            .distinct()
        )
        role_ids = [row[0] for row in role_ids_query.all()]
        
        print(f"用户角色ID: {role_ids}")
        
        if role_ids:
            # 查询这些角色的应用权限
            app_codes_query = (
                session.query(RoleAppEntity.app_code)
                .filter(RoleAppEntity.role_id.in_(role_ids))
                .distinct()
            )
            allowed_app_codes = [row[0] for row in app_codes_query.all()]
            
            print(f"允许的应用: {allowed_app_codes}")
            
            if allowed_app_codes:
                print(f"✓ 该用户应该只能看到这些应用: {', '.join(allowed_app_codes)}")
            else:
                print("ℹ 该用户可以看到所有应用(无限制)")
        else:
            print("✗ 该用户没有角色")

if __name__ == "__main__":
    print("DB-GPT 应用权限调试工具")
    print("=" * 60)
    
    try:
        # 检查配置
        check_permission_config()
        
        # 测试特定用户
        print("\n" + "=" * 60)
        user_id_input = input("\n请输入要测试的用户ID (直接回车跳过): ").strip()
        if user_id_input:
            try:
                user_id = int(user_id_input)
                test_api_filter(user_id)
            except ValueError:
                print("无效的用户ID")
        
        print("\n" + "=" * 60)
        print("检查完成！")
        print("=" * 60)
        
        print("\n如果权限配置正确但前端仍能看到所有应用，请检查:")
        print("1. 是否已重启服务")
        print("2. 是否清除了浏览器缓存和localStorage")
        print("3. 是否重新登录获取新的JWT Token")
        print("4. 查看服务器日志中是否有权限过滤的日志:")
        print("   tail -f logs/dbgpt*.log | grep 'app permission'")
        
    except Exception as e:
        print(f"\n✗ 错误: {e}")
        import traceback
        traceback.print_exc()
